//
//  WBRefreshControl.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/10.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit


enum WBRefresControlType {
    // 下拉刷新
    case normal
    // 松手刷新
    case puling
    // 正在加载
    case refreshing
}

private let WBRefreshHeight: CGFloat = 50

class WBRefreshControl: UIControl {
    
    var refresControlType:WBRefresControlType = .normal {
        
        didSet {
            
            switch refresControlType {
                
            case .normal:
                pullDownImageView.isHidden = false
                indicatorView.stopAnimating()
                messageLabel.text = "下拉刷新"
                
                UIView.animate(withDuration: 0.25, animations: { 
                    
                    self.pullDownImageView.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    
                    if oldValue == .refreshing {
                        
                        UIView.animate(withDuration: 0.25, animations: { 
                            
                            self.currentSCrollview?.contentInset.top -= WBRefreshHeight
                        })
                    }
                })
            case .puling:
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.pullDownImageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
                })
                messageLabel.text = "松手就刷新"
            case .refreshing:
                pullDownImageView.isHidden = true
                indicatorView.startAnimating()
                messageLabel.text = "正在刷新"
                UIView.animate(withDuration: 0.25, animations: { 
                    
                    self.currentSCrollview?.contentInset.top += WBRefreshHeight
                })
                
                sendActions(for: .valueChanged)
                
            }
            
        }
        
    }
    // 滚动视图
    var currentSCrollview: UIScrollView?
    // 箭头
    fileprivate lazy var pullDownImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 提示信息
    fileprivate lazy var messageLabel: UILabel = {
       
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = "下拉刷新"
        label.textColor = UIColor.darkGray

        return label
    }()
    // 菊花
    fileprivate lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor.red
        
        // 添加子控件
        addSubview(pullDownImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        pullDownImageView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        // 约束
        addConstraint(NSLayoutConstraint(item: pullDownImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pullDownImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: pullDownImageView, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .left, relatedBy: .equal, toItem: pullDownImageView, attribute: .right, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: pullDownImageView, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: pullDownImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        indicatorView.startAnimating()
        
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        if newSuperview is UIScrollView {
            
            let scrollView = newSuperview as! UIScrollView
            
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
            
            self.frame.size.width = scrollView.bounds.size.width
            self.frame.size.height = WBRefreshHeight
            // 设置Y坐标
            self.frame.origin.y = -WBRefreshHeight

            currentSCrollview = scrollView
        }
    }
    // kvo监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let contentOffsetY = currentSCrollview!.contentOffset.y
        
        if currentSCrollview!.isDragging {
            
            let limitMaxY = -(currentSCrollview!.contentInset.top + WBRefreshHeight)
            
            if contentOffsetY < limitMaxY &&  refresControlType == .normal{
                
                refresControlType = .puling
                
            }else if contentOffsetY >= limitMaxY && refresControlType == .puling {
                
                refresControlType = .normal
                
            }
        } else {
            
            if refresControlType == .puling {
                
                refresControlType = .refreshing
            }
        }
    }
    
    func endRefreshing() {
        
        refresControlType = .normal
    }
    // 移除kvo
    deinit {
        
        currentSCrollview?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
